package com.work.work.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.work.work.dto.ProjectStatusStatDTO;
import com.work.work.dto.TaskProgressDTO;
import com.work.work.entity.Progress;
import com.work.work.entity.Project;
import com.work.work.entity.Task;
import com.work.work.mapper.ProgressMapper;
import com.work.work.mapper.ProjectMapper;
import com.work.work.mapper.TaskMapper;
import com.work.work.service.ProgressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ProgressServiceImpl extends ServiceImpl<ProgressMapper, Progress> implements ProgressService {
    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private ProjectMapper projectMapper;


    @Override
    public List<TaskProgressDTO> getProjectProgress(Integer projectId) {
        // 查询项目下的所有任务
        LambdaQueryWrapper<Task> taskWrapper = new LambdaQueryWrapper<>();
        taskWrapper.eq(Task::getProjectId, projectId);
        List<Task> tasks = taskMapper.selectList(taskWrapper);

        return tasks.stream()
                .map(this::convertToTaskProgressDTO)
                .toList();
    }

    @Override
    public TaskProgressDTO getTaskProgress(Integer taskId) {
        Task task = taskMapper.selectById(taskId);
        if (task == null) {
            return null;
        }
        return convertToTaskProgressDTO(task);
    }

    @Override
    public List<TaskProgressDTO> getOverdueTasks() {
        LocalDateTime now = LocalDateTime.now();
        LambdaQueryWrapper<Task> taskWrapper = new LambdaQueryWrapper<>();
        taskWrapper.lt(Task::getEndTime, now)
                  .ne(Task::getStatus, 3); // 不等于已完成状态

        List<Task> tasks = taskMapper.selectList(taskWrapper);
        return tasks.stream()
                .map(this::convertToTaskProgressDTO)
                .toList();
    }

    @Override
    public List<TaskProgressDTO> getTasksByStatus(Integer status) {
        LambdaQueryWrapper<Task> taskWrapper = new LambdaQueryWrapper<>();
        taskWrapper.eq(Task::getStatus, status);

        List<Task> tasks = taskMapper.selectList(taskWrapper);
        return tasks.stream()
                .map(this::convertToTaskProgressDTO)
                .toList();
    }

    @Override
    public List<ProjectStatusStatDTO> getProjectStatusStats() {
        // 获取所有项目
        List<Project> projects = projectMapper.selectList(null);
        LocalDateTime now = LocalDateTime.now();

        // 初始化统计数据
        Map<String, Integer> statsMap = new LinkedHashMap<>();
        statsMap.put("未开始", 0);
        statsMap.put("进行中", 0);
        statsMap.put("已完成", 0);
        statsMap.put("已逾期", 0);

        // 统计各状态项目数量
        for (Project project : projects) {
            if (project.getStatus() == 3) {
                statsMap.merge("已完成", 1, Integer::sum);
            } else if (project.getStatus() == 2) {
                statsMap.merge("进行中", 1, Integer::sum);
            } else if (project.getStatus() == 1) {
                statsMap.merge("未开始", 1, Integer::sum);
            } else if (project.getEndTime() != null && project.getEndTime().isBefore(now)) {
                statsMap.merge("已逾期", 1, Integer::sum);
            } else {
                // 默认情况，可以根据需要处理
                statsMap.merge("已逾期", 1, Integer::sum);
            }
        }
        // 转换为DTO列表
        return statsMap.entrySet().stream()
                .map(entry -> {
                    ProjectStatusStatDTO dto = new ProjectStatusStatDTO();
                    dto.setName(entry.getKey());
                    dto.setValue(entry.getValue());
                    return dto;
                })
                .collect(Collectors.toList());
    }

    private TaskProgressDTO convertToTaskProgressDTO(Task task) {
        TaskProgressDTO dto = new TaskProgressDTO();

        // 设置任务基本信息
        dto.setTaskId(task.getId());
        dto.setTaskName(task.getTaskName());
        dto.setProjectId(task.getProjectId());
        dto.setAssignee(task.getAssignee());
        dto.setStartTime(task.getStartTime());
        dto.setEndTime(task.getEndTime());

        // 获取项目名称
        Project project = projectMapper.selectById(task.getProjectId());
        if (project != null) {
            dto.setProjectName(project.getProjectName());
        }

        // 获取最新进度
        LambdaQueryWrapper<Progress> progressWrapper = new LambdaQueryWrapper<>();
        progressWrapper.eq(Progress::getTaskId, task.getId())
                      .orderByDesc(Progress::getUpdateTime)
                      .last("LIMIT 1");

        Progress progress = getOne(progressWrapper);
        if (progress != null) {
            dto.setProgressPercentage(progress.getProgressPercentage());
            dto.setUpdateTime(progress.getUpdateTime());
        }

        // 计算状态
        LocalDateTime now = LocalDateTime.now();
        if (task.getStatus() == 3) {
            dto.setStatus(3); // 已完成
        } else if (task.getEndTime() != null && task.getEndTime().isBefore(now)) {
            dto.setStatus(4); // 已逾期
        } else if (task.getStartTime() != null && task.getStartTime().isAfter(now)) {
            dto.setStatus(1); // 未开始
        } else {
            dto.setStatus(2); // 进行中
        }

        return dto;
    }
}